package com.weshare.transform;


import com.weshare.apitest.beans.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class TransformTest2_Reduce {

    public static void main(String[] args) throws Exception {

        // 创建流处理的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 从文件中读取数据
        String inputPath = "D:\\idea-workspace\\flink-learn\\src\\main\\resources\\sensor.txt";
        DataStream<String> inputStream = env.readTextFile(inputPath);

        // 转换读取的对象
        DataStream<SensorReading> dataStream = inputStream.map(new MapFunction<String, SensorReading>() {
            @Override
            public SensorReading map(String value) throws Exception {
                String[] strings = value.split(",");
                System.out.println(strings);
                return new SensorReading(strings[0], Long.valueOf(strings[1]), Double.parseDouble(strings[2]));

            }
        });
        //分组
        KeyedStream<SensorReading, String> keyedStream = dataStream.keyBy(SensorReading::getId);

        // Reduce 聚合  取温度的最大值及当前温度的最新时间戳
        SingleOutputStreamOperator<SensorReading> reduceResult = keyedStream.reduce((ReduceFunction<SensorReading>) (value1, value2) -> {
            SensorReading sensorReading = new SensorReading(value1.getId(), value2.getTimeStamp(), Math.max(value1.getTemperature(), value2.getTemperature()));
            return sensorReading;
        });

        reduceResult.print();

        // 执行
        env.execute();
    }
}
